package handler

import (
	"cmsuite/cache"
	"cmsuite/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Create(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.News{
		Title:   title,
		Content: content,
		Img:     img,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redid_key := "news_" + strconv.Itoa(int(data.ID))
	var news model.News
	model.DB.Where("id=?", data.ID).First(&news)               //查询数据
	jsonData, _ := json.Marshal(news)                          //转化为json数据
	cache.Rdb.Set(cache.Ctx, redid_key, jsonData, time.Hour*2) //保存到redis中
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	var news model.News
	model.DB.Where("id=?", id).Delete(&news)
	redid_key := "news_" + id
	cache.Rdb.Del(cache.Ctx, redid_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {
	var news []model.News
	redis_key := "new_list"
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		model.DB.Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &news)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": news,
	})
	return
}
